﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Valor.DBUtility.MSSQLHelper;
using xTeam.HengLe.Entity;
using System.Data.SqlClient;
using System.Data;
using ShopB2C.Entity;

namespace xTeam.Hengle.DataAccess {
    public class ProductDataAccess {
        private bool _isCN = true;
        private int _subNameLength = 16;
        /// <summary>
        /// 会员折扣
        /// </summary>
        private const string _discount = "Product_Discount_List";
        /// <summary>
        /// 保存会员折扣
        /// </summary>
        private const string _discountMember = "Product_Discount_Member";
        private const string _batchDiscount = "Product_BatchDiscount";
        private const string _extendList = "Product_Extend_List";
        private const string _saveExtend = "Product_Extend_Save";
        private const string _deleteExtend = "Product_Extend_Delete";

        public ProductDataAccess(string connectionString, string langName) {
            SQLProcedureHelper.ConnectionString = connectionString;
            this._isCN = langName.ToLower() == "en-us" ? false : true;
        }


        public int SaveBase(EProduct prdouct) {
            int result = 0;
            SqlParameter[] parameters = 
            {
                new SqlParameter("@productname",SqlDbType.NVarChar,255){Value=prdouct.ProductName},
                new SqlParameter("@description",SqlDbType.NVarChar,255){Value=prdouct.Description},
                new SqlParameter("@keywords",SqlDbType.NVarChar,255){Value=prdouct.KeyWords},
                new SqlParameter("@productno",SqlDbType.NVarChar,20){Value=prdouct.ProductNo},
                new SqlParameter("@classid",SqlDbType.Int){Value=prdouct.ClassId},
                new SqlParameter("@ProductId",SqlDbType.Int){Value=prdouct.ProductId},
                new SqlParameter("@IsActive",SqlDbType.Bit){Value=prdouct.IsActive},
                new SqlParameter("@StockCount",SqlDbType.Int){Value=prdouct.StockCount},
                new SqlParameter("@SubName",SqlDbType.NVarChar,50){Value = prdouct.SubName},
                new SqlParameter("@BrandName",SqlDbType.NVarChar,50){Value = prdouct.BrandName}
            };

            result = Convert.ToInt32(SQLProcedureHelper.ExecuteScalar(this._isCN ? "product_update" : "product_update_en", parameters));
            return result;
        }

        public List<EProduct> Search(int pageSize, int pageIndx, int classId, string key, int uid, DateTime? archive, ref int pageCount) {
            List<EProduct> productList = new List<EProduct>();

            SqlParameter[] parameter = 
            {
                new SqlParameter("@classid",SqlDbType.Int){Value=classId},
                new SqlParameter("@PageIndex",SqlDbType.Int){Value=pageIndx},
                new SqlParameter("@PageSize",SqlDbType.Int){Value=pageSize},
                new SqlParameter("@key",SqlDbType.NVarChar,50){Value = key},
                new SqlParameter("@Uid",SqlDbType.Int){Value = uid},
                new SqlParameter("@Archive",SqlDbType.DateTime){Value = archive}
            };
            SqlDataReader reader = SQLProcedureHelper.ExecuteReader(this._isCN ? "product_selectList" : "product_selectList_en", parameter);
            while (reader.Read()) {
                pageCount = Convert.ToInt32(reader["PageCount"]);
                string productName = reader["ProductName"].ToString();
                string subName = reader["SubName"].ToString();

                subName = string.IsNullOrEmpty(subName) ? productName : subName;
                subName = subName.Substring(0, subName.Length >= _subNameLength ? _subNameLength : subName.Length);

                productList.Add(new EProduct() {
                    ProductId = Convert.ToInt32(reader["ProductId"]),
                    SubName = subName,
                    DisCount = Convert.ToDecimal(reader["Discount"]),
                    MyDisCount = Convert.ToDecimal(reader["MyDiscount"]),
                    Price = Convert.ToDecimal(reader["Price"]),
                    Description = reader["Description"].ToString(),
                    KeyWords = reader["KeyWords"].ToString(),
                    ProductName = productName,
                    ProductNo = reader["ProductNo"].ToString(),
                    AddDateTime = Convert.ToDateTime(reader["AddDateTime"]),
                    ImageName = reader["ImageName"].ToString(),
                    BrandName = reader["BrandName"].ToString()
                });
            };
            reader.Close();

            return productList;
        }

        public EProduct GetBaseById(int productId, int uid) {
            EProduct product = null;

            SqlParameter[] parameter = 
            { 
                new SqlParameter("@ProductId", SqlDbType.Int) { Value = productId } ,
                new SqlParameter("@Uid",SqlDbType.Int){Value =uid }
            };

            SqlDataReader reader = SQLProcedureHelper.ExecuteReader(this._isCN ? "product_select" : "product_select_en", parameter);
            if (reader.HasRows) {
                product = new EProduct();

                while (reader.Read()) {
                    product.ClassId = Convert.ToInt32(reader["ClassId"]);
                    product.ProductId = Convert.ToInt32(reader["ProductId"]);
                    product.Description = reader["Description"].ToString();
                    product.ProductNo = reader["ProductNo"].ToString();
                    product.KeyWords = reader["KeyWords"].ToString();
                    product.ProductName = reader["ProductName"].ToString();
                    product.SubName = reader["SubName"].ToString();
                    product.ImageName = reader["ImageName"].ToString();
                    product.IsActive = Convert.ToBoolean(reader["IsActive"]);
                    product.StockCount = Convert.ToInt32(reader["StockCount"]);
                    product.DisCount = Convert.ToDecimal(reader["DisCount"]);
                    product.MyDisCount = Convert.ToDecimal(reader["MyDiscount"]);
                    product.BrandName = reader["BrandName"].ToString();
                    product.Price = Convert.ToDecimal(reader["Price"]);
                }
            }
            reader.Close();
            return product;
        }

        public EProductDetails GetDeatails(int productid) {
            EProductDetails details = new EProductDetails() {
                Services = string.Empty,
                PackList = string.Empty,
                FullSnap = string.Empty,
                Detail = string.Empty,
                Description = string.Empty,
                ProductId = productid
            };

            SqlParameter[] parameter = 
            {
                new SqlParameter("@productid",SqlDbType.Int){Value=productid}
            };

            SqlDataReader reader = SQLProcedureHelper.ExecuteReader(this._isCN ? "Product_Details_Select" : "Product_Details_Select_en", parameter);
            if (reader.HasRows) {
                reader.Read();
                details.Detail = reader["Detail"].ToString();
                details.FullSnap = reader["FullSnap"].ToString();
                details.PackList = reader["PackList"].ToString();
                details.Services = reader["Services"].ToString();
                details.Description = reader["Description"].ToString();
            }

            return details;
        }

        public int SaveDetails(EProductDetails details) {
            int result = 0;
            SqlParameter[] parameter = 
            {
                new SqlParameter("@Services",SqlDbType.NVarChar,50){Value=details.Services},
                new SqlParameter("@Details",SqlDbType.NVarChar,3500){Value=details.Detail},
                new SqlParameter("@ProductId",SqlDbType.Int){Value = details.ProductId}

            };

            result = SQLProcedureHelper.ExecuteNonQuery(this._isCN ? "Product_Details_Save" : "Product_Details_Save_en", parameter);

            return result;
        }

        public int SaveImage(EProductImage image) {
            int result = 0;
            SqlParameter[] parameters = 
            {
               new SqlParameter("@ImageId",SqlDbType.Int),
               new SqlParameter("@ImageName",SqlDbType.NVarChar,50),
               new SqlParameter("@Title",SqlDbType.NVarChar,255),
               new SqlParameter("@Description",SqlDbType.NVarChar,1000),
               new SqlParameter("@IsCover",SqlDbType.Bit),
               new SqlParameter("@ProductId",SqlDbType.Int),
               new SqlParameter("@Sequence",SqlDbType.Int)
            };

            parameters[0].Value = image.ImageId;
            parameters[1].Value = image.ImageName;
            parameters[2].Value = image.Title;
            parameters[3].Value = image.Description;
            parameters[4].Value = image.IsCover;
            parameters[5].Value = image.ProductId;
            parameters[6].Value = image.Sequence;

            result = SQLProcedureHelper.ExecuteNonQuery(this._isCN ? "Product_Image_Save" : "Product_Image_Save_en", parameters);

            return result;
        }

        public int SetCover(int imageId) {
            int result = 0;
            SqlParameter[] parameters =
            {
                new SqlParameter("@ImageId",SqlDbType.Int)
            };
            parameters[0].Value = imageId;
            result = SQLProcedureHelper.ExecuteNonQuery(this._isCN ? "Product_Image_SetCover" : "Product_Image_SetCover_en", parameters);
            return result;
        }

        public List<EProductImage> GetImageList(int productId) {
            List<EProductImage> imageList = new List<EProductImage>();

            SqlParameter[] parameters = 
            {
                new SqlParameter("@ProductId",SqlDbType.Int)
            };
            parameters[0].Value = productId;

            SqlDataReader reader = SQLProcedureHelper.ExecuteReader(this._isCN ? "Product_Image_List" : "Product_Image_List_en", parameters);
            if (reader.HasRows) {
                while (reader.Read()) {
                    imageList.Add(new EProductImage() {
                        Description = reader["Description"].ToString(),
                        ImageId = Convert.ToInt32(reader["ImageId"]),
                        ImageName = reader["ImageName"].ToString(),
                        IsCover = Convert.ToBoolean(reader["IsCover"]),
                        ProductId = Convert.ToInt32(reader["ProductId"]),
                        Sequence = Convert.ToInt32(reader["Sequence"]),
                        Title = reader["Title"].ToString()
                    });
                }
            }
            reader.Close();

            return imageList;
        }

        public List<EProductImage> DeleteImage(string[] ids) {
            List<EProductImage> imageList = new List<EProductImage>();
            foreach (var item in ids) {
                SqlParameter[] parameters = 
                {
                   new  SqlParameter("@ImageId",SqlDbType.Int)
                };
                parameters[0].Value = item;
                SqlDataReader reader = SQLProcedureHelper.ExecuteReader(this._isCN ? "Product_Image_Delete" : "Product_Image_Delete_en", parameters);
                while (reader.Read()) {
                    imageList.Add(new EProductImage() {
                        ImageName = reader["ImageName"].ToString(),
                        ProductId = Convert.ToInt32(reader["ProductId"])
                    });
                }
                reader.Close();
            }
            return imageList;
        }

        public int UpdateImageDescription(int imageId, string title, string description, int sequence) {
            return SQLProcedureHelper.ExecuteNonQuery(this._isCN ? "Product_Image_UpdateDescription" : "Product_Image_UpdateDescription_en",
                new SqlParameter[] {
                    new SqlParameter("@ImageId",SqlDbType.Int){Value=imageId}
                    ,new SqlParameter("@Title",SqlDbType.NVarChar,50){Value=title}
                    ,new SqlParameter("@Description",SqlDbType.NVarChar,255){Value= description}
                    ,new SqlParameter("@Sequence",SqlDbType.Int){Value=sequence} });
        }

        public int Delete(int productId) {
            return SQLProcedureHelper.ExecuteNonQuery(this._isCN ? "product_delete" : "product_delete_en"
                , new SqlParameter[]{
                    new SqlParameter("@ProductId",SqlDbType.Int){Value = productId}});
        }

        /// <summary>
        /// 会员组打折
        /// </summary>
        /// <param name="productId">关联的产品ID</param>
        /// <returns>折扣表</returns>
        public List<UserLevelEntity> MemberDiscount(int productId) {
            List<UserLevelEntity> list = new List<UserLevelEntity>();
            SqlParameter[] parameters = 
            {
                new SqlParameter("@ProductId",SqlDbType.Int){Value = productId}
            };

            SqlDataReader reader = SQLProcedureHelper.ExecuteReader(string.Format("{0}{1}", _discount, _isCN ? string.Empty : "_en"), parameters);
            while (reader.Read()) {
                list.Add(new UserLevelEntity() {
                    Name = reader["Name"].ToString(),
                    LevelId = Convert.ToInt32(reader["LevelId"]),
                    IsDiscount = Convert.ToBoolean(reader["IsDiscount"]),
                    Discount = Convert.ToDecimal(reader["Discount"])
                });
            }
            return list;
        }

        /// <summary>
        /// 保存会员价格
        /// </summary>
        /// <param name="memberPrice">会员价实体类</param>
        /// <returns>被影响的行</returns>
        public int SaveMemberDiscount(UserLevelEntity memberPrice) {
            int result = 0;
            SqlParameter[] parameters = 
            {
                new SqlParameter("@Levelid",SqlDbType.Int){Value = memberPrice.LevelId },
                new SqlParameter("@ProductId",SqlDbType.Int){Value = memberPrice.Sequence},
                new SqlParameter("@Discount",SqlDbType.Float){Value = memberPrice.Discount},
                new SqlParameter("@IsDiscount",SqlDbType.Bit){Value = memberPrice.IsDiscount}
            };
            result = SQLProcedureHelper.ExecuteNonQuery(string.Format("{0}{1}", _discountMember, _isCN ? string.Empty : "_en"), parameters);

            return result;
        }

        public int BatchDiscount(int productId, decimal price, decimal discount) {
            int result = 0;
            SqlParameter[] parameters = 
            {
                new SqlParameter("@ProductId",SqlDbType.Int){Value = productId },
                new SqlParameter("@Price",SqlDbType.Decimal){Value = price},
                new SqlParameter("@Discount",SqlDbType.Decimal){Value = discount}
            };
            result = SQLProcedureHelper.ExecuteNonQuery(string.Format("{0}{1}", _batchDiscount, _isCN ? string.Empty : "_En"), parameters);

            return result;
        }

        public List<ProductExtendEntity> ProductExtendList(int productId) {
            List<ProductExtendEntity> extendList = new List<ProductExtendEntity>();
            SqlParameter[] parameters =
            {
                new SqlParameter("@ProductId",SqlDbType.Int)
                                        };
            parameters[0].Value = productId;

            SqlDataReader reader = SQLProcedureHelper.ExecuteReader(string.Format("{0}{1}", _extendList, _isCN ? "" : "_en"), parameters);

            while (reader.Read()) {
                extendList.Add(new ProductExtendEntity() {
                    ExtendKey = reader["ExtendKey"].ToString(),
                    ExtendValue = reader["ExtendValue"].ToString(),
                    ExtendId = Convert.ToInt32(reader["ExtendId"]),
                    ProductId = Convert.ToInt32(reader["ProductId"]),
                    Sequence = Convert.ToInt32(reader["Sequence"])

                });
            }
            reader.Close();
            return extendList;
        }

        public int SaveExtend(ProductExtendEntity extnedEntity) {
            int result = 0;

            SqlParameter[] parameters = 
            {
                new SqlParameter("@ProductId",SqlDbType.Int)
                , new SqlParameter("@ExtendKey",SqlDbType.NVarChar,50)
                , new SqlParameter("@ExtendValue",SqlDbType.NVarChar,1000)
                , new SqlParameter("@Sequence",SqlDbType.Int)
                , new SqlParameter("@ExtendId",SqlDbType.Int)
            };

            parameters[0].Value = extnedEntity.ProductId;
            parameters[1].Value = extnedEntity.ExtendKey;
            parameters[2].Value = extnedEntity.ExtendValue;
            parameters[3].Value = extnedEntity.Sequence;
            parameters[4].Value = extnedEntity.ExtendId;

            result = SQLProcedureHelper.ExecuteNonQuery(string.Format("{0}{1}", _saveExtend, _isCN ? string.Empty : "_en"), parameters);

            return result;
        }

        public int DeleteExtendItem(int extendId) {
            int result = 0;

            SqlParameter[] parameters = 
           {
               new SqlParameter("@ExtendId",SqlDbType.Int)
           };

            parameters[0].Value = extendId;
            result = SQLProcedureHelper.ExecuteNonQuery(string.Format("{0}{1}", _deleteExtend, _isCN ? string.Empty : "_en"), parameters);

            return result;
        }
    }
}
